package shuzu;

public class _03Z字型打印矩阵 {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
                // {13, 14, 15, 16},
        };
        print(matrix);
    }

    private static void print(int[][] matrix) {
        int r = 0, m = matrix.length;
        int c = 0, n = matrix[0].length;
        Boolean l2r = true;//true代表从坐下往右上走
        while (r < m && c < n) {
            if (l2r) {
                //从坐下走到右上
                System.out.print(matrix[r][c] + " ");
                if (r == 0 && c < n - 1) {
                    //处于第一行，列还没有走到结尾,只能向右走
                    l2r = !l2r;
                    c++;
                    continue;
                } else if (r > 0 && c == n - 1) {
                    //最后一列，只能向下走
                    l2r = !l2r;
                    r++;
                    continue;
                } else {
                    r--;
                    c++;
                }
            } else {
                //走下坡
                System.out.print(matrix[r][c] + " ");
                if (c == 0 && r < m - 1) {//走到第一列，只能往下走
                    l2r = !l2r;
                    r++;
                    continue;
                } else if (r == m - 1) {//到最后一行，只能往右走
                    l2r = !l2r;
                    c++;
                    continue;
                } else {
                    r++;
                    c--;
                }
            }
        }
    }
}
